import React, { PureComponent } from 'react';
import queryString from 'query-string';
import { connect } from 'dva';
import { Form } from '@ant-design/compatible';
import '@ant-design/compatible/assets/index.css';
import { Row, Col, Card, Input, Button, Tabs, Spin } from 'antd';
import StandardTable from '@/components/StandardTable';
import PageHeaderWrapper from '@/components/PageHeaderWrapper';
import Link from 'umi/link';
import styles from '@/utils/utils.less';

const { TabPane } = Tabs;
@connect(({ guide, publicdata, loading, login, handle }) => ({
  login,
  guide,
  publicdata,
  handle,
  loading: loading.models.guide,
}))
@Form.create()
class GuideList extends PureComponent {
  state = {
    selectedRows: [],
    selectedKeys: [],
  };

  componentDidMount() {
    const {
      location,
      guide: {
        data: { pagination },
      },
      dispatch,
    } = this.props;
    const { isMenuLink } = location.query;
    dispatch({
      type: 'guide/tabList',
      payload: ['BIZ_INS_TYPE', 'BIZ_ACCU_TYPE'],
    }).then(res => {
      const {
        guide: { activeKey },
      } = this.props;
      const tempActiveKey = queryString.parse(location.search).activeKey || activeKey;
      if (res) {
        if (isMenuLink) {
          this.resetAndGeLlist(location);
        } else {
          this.getList(tempActiveKey, pagination.current, pagination.pageSize);
        }
      }
    });
  }

  // componentWillUnmount() {
  //   const { dispatch } = this.props;
  //   const param = {
  //     formFieldsValue: {},
  //     tabList: [],
  //     data: {
  //       list: [],
  //       pagination: {
  //         current: 1,
  //         pageSize: 10,
  //         total: 0,
  //       },
  //     },
  //   };
  //   dispatch({
  //     type: 'guide/updateModelData',
  //     payload: param,
  //   });
  // }

  getList = (activeKey, currentPage = 1, pageSize = 10) => {
    const { dispatch, form } = this.props;
    form.validateFields((err, fieldsValue) => {
      dispatch({
        type: 'guide/updateModelData',
        payload: { formFieldsValue: fieldsValue, activeKey },
      });
      if (err) return;
      const pageArg = { currentPage, pageSize };
      dispatch({
        type: 'guide/fetchList',
        payload: {
          plcyInfoVo: {
            keyWord: fieldsValue.keyWord ? fieldsValue.keyWord.trim() : fieldsValue.keyWord,
            type: activeKey,
          },
          pageArg,
        },
      });
    });
  };

  // 重置
  resetSearch = () => {
    const { form, dispatch } = this.props;
    form.resetFields();
    dispatch({
      type: 'guide/updateModelData',
      payload: { formFieldsValue: {} },
    });
  };

  handleSelectRows = (selectedRows, selectedKeys) => {
    this.setState({ selectedRows, selectedKeys });
  };

  tabChange = activeKey => {
    this.setState({ selectedRows: [] }, () => {
      this.getList(activeKey);
    });
  };

  handleStandardTableChange = pagination => {
    const {
      guide: { activeKey },
    } = this.props;
    this.getList(activeKey, pagination.current, pagination.pageSize);
  };

  // 重置查询条件并获取列表
  async resetAndGeLlist(location) {
    const {
      dispatch,
      guide: { tabList },
    } = this.props;
    if (tabList.length) {
      await this.resetSearch();
      await this.getList(tabList[0].itemCode);
      dispatch({
        type: 'guide/updateModelData',
        payload: { expandForm: false },
      });
      dispatch({
        type: 'global/changeIsMenuLink',
        payload: location,
      });
    }
  }

  render() {
    const { selectedRows, selectedKeys } = this.state;
    const {
      guide: { data, tabList, formFieldsValue, activeKey },
      loading,
      form,
    } = this.props;
    const { getFieldDecorator } = form;
    const columns = [
      {
        title: '标题',
        dataIndex: 'tit',
        onHeaderCell: () => ({
          style: {
            fontWeight: 'bold',
          },
        }),
      },
      {
        title: '操作',
        dataIndex: 'operation',
        width: 200,
        onHeaderCell: () => ({
          style: {
            fontWeight: 'bold',
            textAlign: 'center',
          },
        }),
        onCell: () => ({
          style: {
            textAlign: 'center',
          },
        }),
        render: (text, record) => (
          <Link to={`/searchmanage/guide/detail?id=${record.plcyId}`}>查看</Link>
        ),
      },
    ];

    const tabPane1 = (
      <div>
        <StandardTable
          selectedRows={selectedRows}
          selectedRowKeys={selectedKeys}
          loading={loading}
          data={data}
          columns={columns}
          rowKey="plcyId"
          onSelectRow={this.handleSelectRows}
          onChange={this.handleStandardTableChange}
        />
      </div>
    );
    const tabPaneTem = ['', '', tabPane1, tabPane1, tabPane1, tabPane1, tabPane1, tabPane1];

    return (
      <PageHeaderWrapper>
        <Card className={styles.searchCard}>
          <Row style={{ marginBottom: 24 }}>
            <Col span={12} offset={7}>
              {getFieldDecorator('keyWord', {
                initialValue: formFieldsValue.keyWord,
                rules: [{ required: false }],
              })(
                <Input placeholder="请输入" style={{ width: '70%', float: 'left' }} size="large" />
              )}
              <Button
                type="primary"
                size="large"
                htmlType="submit"
                style={{ marginLeft: -4, borderRadius: '0 4px 4px 0', float: 'left' }}
                onClick={() => this.getList(activeKey)}
              >
                搜索
              </Button>
            </Col>
          </Row>
        </Card>
        <Card className={styles.tabCard}>
          <Spin tip="Loading..." spinning={loading}>
            <Tabs activeKey={activeKey} onChange={this.tabChange}>
              {tabList.map(pane => (
                <TabPane tab={pane.itemName} key={pane.itemCode}>
                  {tabPaneTem[pane.itemCode]}
                </TabPane>
              ))}
            </Tabs>
          </Spin>
        </Card>
      </PageHeaderWrapper>
    );
  }
}

export default GuideList;
